package com.taotao.designpattern.event.proccessor;

import com.taotao.designpattern.event.job.Job;
import lombok.extern.slf4j.Slf4j;

/**
 * @author fanbeibei
 * @version 1.0
 * @date 2021/1/5 15:42
 */
@Slf4j
public abstract class AbstractJobProccessor implements JobProccessor {

    private JobListener jobListener;

    public AbstractJobProccessor(JobListener jobListener) {
        this.jobListener = jobListener;
    }

    @Override
    public void triggerJob(Job job) {
        //1. 触发前检查
        if (jobListener.beforeTrigger(job)) {
            try {
                validNotPass(job, System.currentTimeMillis());
            } catch (Exception e) {
                log.error("", e);
            }
            return;
        }

        //2. 触发任务
        JobTriggerResult triggerResult = triggerJob0(job);
        if (null == triggerResult) {
            throw new IllegalStateException("method triggerJob0 must not return null !!");
        }

        jobListener.onTriggerResult(triggerResult);
    }


    @Override
    public void proccessJobRunResult(JobRunResult runResult) {
        try {
            jobListener.onRunResult(runResult);
        } catch (Exception e) {
            log.error("", e);
        }

        try {
            jobListener.onJobComplete(runResult);
        } catch (Exception e) {
            log.error("", e);
        }
    }


    /**
     * 任务未校验通过
     *
     * @param job
     * @param currentTimeMillis
     */
    protected abstract void validNotPass(Job job, long currentTimeMillis);

    /**
     * 触发任务的逻辑
     *
     * @param job
     * @return
     */
    protected abstract JobTriggerResult triggerJob0(Job job);


}
